package managers.socialNetworkManagers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Properties;

import javax.swing.ImageIcon;

import managers.OptionsManager;
import utils.ImageUtils;
import utils.StackTracePrinter;


public class CacheManager {

	private CacheManager () {
	}
	
	private static Properties options = OptionsManager.getSharedInstance().getOptionGroup("fileTransfer");

	public static void saveImage (byte[] image, String name) throws IOException {
		FileOutputStream fos = new FileOutputStream(options.getProperty("cacheFolder")+"/"+name);
		fos.write(image);
		fos.close();
	}

	public static ImageIcon retrieveImage (String name, Timestamp lastUpdate) throws IOException {
		File f = new File (options.getProperty("cacheFolder")+"/"+name);
		if (f.exists()) {
			if (lastUpdate != null) {
				if (new Date(f.lastModified()).compareTo(lastUpdate) < 0) {
					return null;
				}
			}
			FileInputStream fis = new FileInputStream(f);
			byte[] bytes = new byte[(int) f.length()];
			fis.read(bytes);
			return ImageUtils.bytesToImage(bytes, null);
		}
		return null;
	}


	public static final int SMALL = 0;
	public static final int MEDIUM = 1;
	public static final int LARGE = 2;

	public static String formatEventName (int eventId) {
		return "event_"+eventId+".jpg";
	}
	
	public static String formatPhotoName (int photoId, int size) {
		return "photo_"+photoId+"_"+size+".jpg";
	}

	public static String formatAlbumName (int albumId) {
		return "album_"+albumId+".jpg";
	}

	public static String formatPersonalPhotoName (int userId, int size) {
		return "userPhoto_"+userId+"_"+size+".jpg";
	}
	
	public static String formatFamilyPhotoName (int photoId) {
		return "familyPhoto_"+photoId+".jpg";
	}

	public static void copyfile(File input, File output) throws IOException {

			InputStream in = new FileInputStream(input);
			OutputStream out = new FileOutputStream(output);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0){
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
	}
}